<template>
  <div class="position: relative; border: 1px solid blue;">
    
    <!-- 导航标签 -->
    <!-- <page-header-wrapper :title="false" style="position: relative; top: 0; left: 0; width: 100%;"></page-header-wrapper> -->
    
    <!-- 主体内容 -->
    <div :style="viewHeight?{'height':viewHeight+'px'}:{}" class="content-common-wrap">
      
      <!-- loading -->
      <a-spin v-if="cardTableLoading" style="position: absolute; left: 50%; top: 50%; z-index: 9999; transform: translate(-50%, -50%);" />
      
      <!-- 操作栏 -->
      <OperationBar
        @cardTableSwitch="switchCardTable"
        @searchChange="searchChange"
        @columnChange="resetColumn"
        @removeItem="removeItem"
        @reloadMsg="reloadMsg"
        @showModal="showModal"
        @showSenior="showSenior"
        :dataSource="dataSource"
      ></OperationBar>

      <!-- 表格部分 -->
      <div class="content-main" :style="viewHeight?{'height':(viewHeight-100)+'px'}:{}">
        
        <!-- 1.卡片表格 -->
        <CardTable
          v-if="isCardTable"
          @cardTableDelete="deleteConfirm"
          @cardTableEdit="makeCardEdit"
          :globalSearchValue="globalSearchValue"
          :sourceData="sourceData"
          :sourceList="sourceList"
          :currentPageConfig="currentPageConfig"
        ></CardTable>
        
        <!-- 2.常规表格 -->
        <!-- {{ selectedRowKeys2 }} -->
        <!-- {{ selectedDoTest }} -->
        <!-- 此数据的二次显示的问题 -->

        <a-table
          :columns="columns"
          :data-source="data"
          :loading="tableLoading"
          :pagination="false"
          :scroll="{ y: viewHeight-150, x: 1200 }"
          :bordered="true"
          :row-selection="rowSelection"
          :hideDefaultSelections="true"
          :sortDirections="['descend', 'ascend']"
          :key="Math.random()"
          v-if="!isCardTable"
        >
          <template slot="index" slot-scope="text, record, index">
            <span>{{ index+1 }}</span>
          </template>

          <template v-for="col in filterParam" :slot="col"  slot-scope="text, record, index">
            <a-row v-html="pointerRed(text, globalSearchValue)" :key="Math.random()"></a-row>
          </template>
          
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            
            <LineAction :record="record" :loopData="[
              { actionName: '编辑-x-' },
              { actionName: '编辑-y-' },
              { actionName: '编辑-z-' },
              { actionName: '编辑-o-' }]"
              @deleteConfirm="deleteConfirm"
            >
            </LineAction>

            <!-- 编辑 -->
            <!-- <a-button type="primary" size="small" v-if="currentPageConfig.update" @click="makeEdit(record.id, record)">{{ $t('app.setting.operation.edit') }}</a-button> -->
            <!-- 删除 -->
            <!-- <a-popconfirm
              :title="$t('app.setting.popconfirm.ask')"
              :ok-text="$t('app.setting.popconfirm.delete')"
              :cancel-text="$t('app.setting.popconfirm.cancel')"
              @confirm="deleteConfirm(record.id)">
              <a-button type="danger" size="small" v-if="currentPageConfig.delete" style="margin-left: 10px;">{{ $t('app.setting.operation.delete') }}</a-button>
            </a-popconfirm> -->
          </template>
        </a-table>
      </div>
      
      <!-- 分页 -->
      <Pagination @paginNewInfo="paginNewInfo"></Pagination>

    </div>


    <!-- 高级搜索 ~ modal -->
    <SeniorModal :seniorSearchInfo="seniorSearchInfo"  @seniorModalSearch="seniorModalSearch" :key="Math.random()"></SeniorModal>


    <!-- 新增编辑 ~ modal -->
    <ModalEdit
      :modalInfoEdit="modalInfoEdit"
      :modalEditStrcture="dataOrigin.editParam"
      v-if="modalInfoEdit.visible"
      :key="Math.random()"
      :requestUrl="dataOrigin.requestUrl"
    ></ModalEdit>

    <ModalAdd
      :modalInfoAdd="modalInfoAdd"
      :modalAddStructure="dataOrigin.addParam"
      v-if="modalInfoAdd.visible"
      :key="Math.random()"
      :requestUrl="dataOrigin.requestUrl"
    ></ModalAdd>

    <!-- 回到顶部小组件  -->
    <BackTop :visibilityHeight="0" />

  </div>
</template>


<script>

// 数据源
const data = [];
// 原始表格形态
const columns = [];
// 内容区域可用高度
import viewObject from '../../utils/viewHeight'
// 回到顶部组件
import { BackTop } from 'ant-design-vue'
// 操作栏-功能按钮
import OperationBar from '../../components/drugCommon/OperationBar'
// 分页组件
import Pagination from '../../components/drugCommon/Pagination'
// 卡片视图
import CardTable from '../../components/drugCommon/CardTable'
// 获取模拟数据
import { listItem, addItem, deleteItem, ModifyItem } from '../../api/data'
// 引入 新增 modal 组件
import ModalAdd from '../../components/drugCommon/ModalAdd'
// 引入 编辑 modal 组件
import ModalEdit from '../../components/drugCommon/ModalEdit'
// 引入 高级搜索 modal 组件
import SeniorModal from '../../components/drugCommon/SeniorModal'
// 引入 store
import store from '../../../src/store'
// 引入 bus
import bus from '@/utils/bus'
// 引入测试 RegExp
import regExpObj from '@/utils/regExp'
// 引入表格行内的操作的组件
import LineAction from '../../components/drugCommon/LineAction'

export default {
  name: 'TableMain',
  props:{
    dataOrigin: Object
  },
  components:{
    BackTop,
    OperationBar,
    Pagination,
    CardTable,
    SeniorModal,
    ModalAdd,
    ModalEdit,
    LineAction
  },
  data(){
    return{
      data,             // 数据源
      columns,          // 原始表格形态
      modalInfoEdit: {       // 编辑的弹框
        visible: false,    // false不显示， true显示
        multi: 1,          // 2-多操作  1-单操作
        sourceData: null,    // 源数据
        id: '',
      },
      modalInfoAdd: {       // 新增的弹框
        visible: false,    // false不显示， true显示
        multi: 1,          // 2-多操作  1-单操作
        sourceData: null,  // 源数据
        id: null
      },
      seniorSearchInfo: {
        visible: false,    // 高级搜索 modal 是否显示
      },

      tableLoading: false,
      viewHeight: viewObject.viewResult,
      // 选中的数据合集
      selectedRowKeys: [],
      selectedDoTest:[],
      isCardTable: false,    // 是否是卡片视图
      globalSearchValue: '', // 描红关键词
      dataSource: [],
      dataSourceChangeCopy: [],
      cardTableSource:[],
      sourceData:[],
      sourceList:[],
      filterParam:[],
      cardTableLoading: false,
      currentPageConfig: {
        add: false,
        cardView: false,
        column: false,
        delete: false,
        export: false,
        query: false,
        reload: false,
        seniorSearch: false,
        update: false
      },
      requestUrl:'',

      // 分页参数
      page: 1,
      pageSize: 10,
    }
  },

  created(){
    // 请求初始数据
    this.listItem();
    this.dataSource = this.dataOrigin.dataSource
    this.dataSourceChangeCopy = this.dataOrigin.dataSourceChangeCopy
    this.columns = this.dataOrigin.columns
    this.requestUrl = this.dataOrigin.requestUrl
  },

  mounted(){


    bus.$on('BusPageConfig', (e) => {
      this.currentPageConfig.add = e.add
      this.currentPageConfig.cardView = e.cardView
      this.currentPageConfig.column = e.column
      this.currentPageConfig.delete = e.delete
      this.currentPageConfig.export = e.export
      this.currentPageConfig.query = e.query
      this.currentPageConfig.reload = e.reload
      this.currentPageConfig.seniorSearch = e.seniorSearch
      this.currentPageConfig.update = e.update
    })

    if(viewObject.isMobile){
      this.switchCardTable()
    }

    setTimeout(()=>{
     console.log("--regExpObj--测试正则对象--", regExpObj)
    }, 3000)
    
  },
  
  watch:{
    // 此处较为神奇，需要仔细研究研究
    // 更新选中的数组数据
    // selectedRowKeys(val1, val2){
    //   console.log("卡片状态-isCardTable-", this.isCardTable);
    //   console.log("--val1的值--", val1);
    //   console.log("--val2的值--", val2);
    // }
  },
  
  methods: {


    /**
     * 排序事件处理
     * pagination:
     * filters:
     * sorter:
     * currentDataSource:
     */
    rankEventListen(pagination, filters, sorter, { currentDataSource }){
      console.log("测试下筛选的状态检测问题-sorter-", sorter);
    },

    // 分页数据按新条件重新请求
    paginNewInfo(param){
      this.page = param.page
      this.pageSize = param.pageSize
      this.listItem()
    },

    // 多个删除操作
    removeItem(){
      if(this.selectedRowKeys.length > 0){
        // 根据数组选择结果生成选中数据的id拼接字符串
        let tempResultPre = []
        this.selectedRowKeys.map((item, index)=>{
          tempResultPre.push(this.data[item].id)
        })
        let tempResult = tempResultPre.join(",")
        this.deleteItem(tempResult)
      }else{
        this.$message.warning( this.$t('app.setting.tipsMsg.pleaseChoose') )
      }
    },

    // 显示新增或者编辑的 modal
    showModal(e){ 
      if(e.type === 2){ // 2-编辑
        if(e.multi === 2 && this.selectedRowKeys.length > 0){  // 选择了数据进行编辑
          let tempIdsArray = []
          this.selectedRowKeys.map((item, index)=>{
            tempIdsArray.push(this.data[item].id)
          })
          this.modalInfoEdit.id = tempIdsArray.join(",")
          this.modalInfoEdit.visible = e.visible
        }else{ // 没有选择数据进行编辑
          this.$message.warning( this.$t('app.setting.tipsMsg.pleaseChoose') );
        }

        // 通用可编辑单个数据或者多个数据, 通过 this.selectedRowKeys 获取数据的id的字符串拼接值
        console.log("测试下编辑情况的选中情况数据--this.selectedRowKeys--", this.selectedRowKeys);

        // 限制单独一个的编辑如下
        // if(e.multi === 2 && this.selectedRowKeys.length < 1 ){
        //   this.$message.warning( this.$t('app.setting.tipsMsg.pleaseChoose') );
        // }else if(e.multi === 2 && this.selectedRowKeys.length > 1){
        //   this.$message.warning( this.$t('app.setting.tipsMsg.onlyOne') );
        // }else if((e.multi === 2 && this.selectedRowKeys.length === 1) || e.multi === 1){
        //   this.modalInfoEdit.id = this.data[this.selectedRowKeys[0]].id
        //   this.modalInfoEdit.visible = e.visible
        // }
      }else{ // 1-新增
        // this.editAndOpenDataInit(null, this.dataOrigin.seniorParam, 1)
        this.modalInfoAdd.visible = e.visible
      }
    },

    // 显示高级搜索
    showSenior(){
      this.seniorSearchInfo.sourceData = this.dataOrigin.seniorParam
      this.seniorSearchInfo.visible = true
    },

    // 高级搜索查询
    seniorModalSearch(e){
      if(this.isCardTable){
        this.cardTableLoading = this.isCardTable
        this.sourceData = []
      }
      this.seniorSearchInfo.visible = false
      this.listItem(e)
    },

    /**
     * 打开编辑或者新增页面的数据状态的初始化处理 
     * @param: data   <Object> 当前编辑或者新增的数据源
     * @param: format <Array>  当前需要显示的 form 组件的格式参数
     * @param: type   <Number> 1-新增, null-编辑
     */
    editAndOpenDataInit(data, format, type){
      if(type){
        format.map((item, index)=>{
          format[index].value = ''
        })
      }else{
        format.map((item, index)=>{
          format[index].value = data[item.keys]
        })
      }
      this.modalInfoEdit.sourceData = format
      this.modalInfoAdd.sourceData = format
    },
    
    /**
     * 表格内部的编辑的点击
     * @param: id      <String> 当前选中数据的id
     * @param: record  <Object> 当前的数据源
     */
    makeEdit(id, record){
      // this.editAndOpenDataInit(record, this.dataOrigin.seniorParam, null)
      this.modalInfoEdit.id = id
      this.modalInfoEdit.visible = true
      console.log("--this.modalInfoEdit.visible--", this.modalInfoEdit.visible);
    },

    // 卡片表格编辑
    makeCardEdit(e){
      this.makeEdit(e.id, e.record)
    },

    /**
     * 表格内部的删除
     * @param: id  <String> 当前选中需要删除的数据的id
     */
    deleteConfirm(id){
      this.deleteItem(id)
    },

    // 删除的请求
    async deleteItem(id){
      let param = {
        id: id,
      }
      if(this.isCardTable){
        this.cardTableLoading = this.isCardTable
        this.sourceData = []
      }
      let responseData = await deleteItem(param);
      if(responseData.code == 200){
        this.$message.success(this.$t('app.setting.tipsMsg.deleteSuccess'));
        // 重新请求数据
        this.listItem();
      }else{
        this.$message.success("数据删除失败！请重试！");
      }
    },

    // 重新刷新页面数据
    reloadMsg(){
      if(this.isCardTable){
        this.cardTableLoading = this.isCardTable
        this.sourceData = []
      }
      this.listItem();
    },

    // 搜索数据的处理
    searchChange(e){
      if(e){
        this.page = 1
        this.pageSize = 10;
      }
      this.globalSearchValue = e;
      this.listItem();
      if(this.isCardTable){
        this.cardTableLoading = this.isCardTable
        this.sourceData = []
      }
    },

    // 获取原始数据
    async listItem(e){

      
      if(e){
        // 高级查询  待定 ~
      }else{
        // 全局普通查询  待定 ~
      }

      this.tableLoading = true;
      let param = {
        globalSearchValue: '',
        senior1: 's1',
        senior2: 's2',
        senior3: 's3',
        senior4: 's4',
        senior5: 's5',
        senior6: 's6',
        pageNum: this.page,
        pageSize: this.pageSize,
      }
      let responseData = await listItem(param, this.requestUrl.add);
      if(responseData.code == 200){
        // 由于排序sort 使用了 template ,数据源中需要增加 key ，不能缺少
        this.data = responseData.data
        this.data.map((item, index)=>{
          this.data[index].key = index
        })
        console.log("终极无敌大keykey：-this.data- ", this.data);
        await this.commonMsgTrans();
        await this.filterParamName();
      }else {
        this.$message.error("数据获取失败！");
      }
      if(this.isCardTable){
        setTimeout(()=>{
          this.cardTableLoading = false;
        }, 500)
      }
      this.tableLoading = false;
    },

    // 关键词描黄
    pointerRed(text, regKey){
      if(regKey){
        // 1.进行关键词过滤处理
        let key = '<span style="background:#FAFAD2; padding: 0px 6px;">'+regKey+'</span>'
        let regular = new RegExp(regKey, 'g')
        let result = String(text).replace(regular, key);
        // 2.返回处理结果
        return result;
      }else{
        return text
      }
    },

    async filterParamName(){
      let tempArr = []
      this.dataSourceChangeCopy.map((item, index)=>{
        if(item.param != 'index' && item.param != 'action'){
          tempArr.push(item.param)
        }
      })
      this.filterParam = tempArr
    },

    // 常规表格数据给卡片表格
    async commonMsgTrans(){
      this.sourceData = this.data
      this.sourceList = this.dataSourceChangeCopy 
    },

    // 回首页
    toHome () {
      this.$router.push({ path: '/' })
    },

    // 单个数据删除
    localDelete(record){
      this.$message.success(this.$t('app.setting.tipsMsg.deleteSuccess'));
    },

    

    // 切换卡片视图
    switchCardTable(){
      this.isCardTable = !this.isCardTable
      if(this.isCardTable){
        this.sourceData = this.data
        this.sourceList = this.dataSourceChangeCopy
      }

      console.log("切换卡片视图-this.isCardTable-", this.isCardTable);
      console.log("切换卡片视图-sourceData-", this.sourceData);
      console.log("切换卡片视图-sourceList-", this.sourceList);


    },

    /**
     * 列操作功能的处理函数
     * param => { index: number, state:boolean }
     * 
     */ 
    resetColumn(param){
      
      console.log("---列操作功能的处理函数--param--", param);
      
      if(param.state){
        let tempObj;
        if(param.index===0){
          tempObj = {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            width: 70,
            scopedSlots: { customRender: 'index' },
            fixed: 'left',
          }
        }else if(param.index === this.dataSource.length-1){
          tempObj = {
            title: '操作',
            key: 'action',
            scopedSlots: { customRender: 'action'},
            width: 140,
            fixed: 'right',
            dataIndex: 'action',
          }
        }else{
          tempObj = {
            title: this.dataSource[param.index].title,
            dataIndex: this.dataSource[param.index].param,
            key: this.dataSource[param.index].param,
            ellipsis: true,
            defaultSortOrder: 'descend',
            sorter: (a, b) => a.age - b.age,
          }
        }
        let modifyIndex = this.locateModifyIndex(param.index, 1, tempObj) // 新增
        if(param.index === 0){
          this.columns.splice(modifyIndex, 0, tempObj)
        }else{
          this.columns.splice(modifyIndex+1, 0, tempObj)
        }
      }else{
        let modifyIndex = this.locateModifyIndex(param.index, 2, null) // 删除
        this.columns.splice(modifyIndex, 1)
      }

      // 重置卡牌数据
      let tempResetArray = [];
      this.columns.map((item, index)=>{
        let obj = {
          title: item.title, 
          param: item.dataIndex, 
          index: index
        }
        tempResetArray.push(obj)
      })
      this.sourceList = tempResetArray
    },

    // 获取真实处理的 index
    locateModifyIndex(locate, type, tempObj){ // locate-原始index  type-操作类型  1-新增 2-删除
      let calcIndex;
      if(type === 2){ 
        this.dataSourceChangeCopy.map((item, index)=>{
          if(item.index === locate){
            calcIndex = index
          }
        })
        this.dataSourceChangeCopy.splice(calcIndex, 1)
      }else if(type === 1 ){
        calcIndex = this.insertCalcIndex(tempObj, locate);
      }
      return calcIndex;
    },

    // 新增加显示的元素的插入位置计算
    insertCalcIndex(tempObj, locate){
      if(this.dataSourceChangeCopy == []){ // 为空随意插
        this.dataSourceChangeCopy.splice(0, 0, tempObj)
      }else{ // 不为空计算位置
        // 寻找当前数据的最小值
        let miniNumber = this.dataSource[locate].index;
        let insertIndex = 0;
        // this.$message.error(locate);
        let tempCycle = this.dataSource.length
        let getResult = false;
        for( let i=0; i < tempCycle; i++){
          if(getResult){
            break; 
          }
          for(let j=0; j < this.dataSourceChangeCopy.length; j++){
            if(Number(miniNumber) + i === Number(this.dataSourceChangeCopy[j].index) ){ 
              insertIndex = j
              getResult = true
              break
            }else if (Number(miniNumber) - i === Number(this.dataSourceChangeCopy[j].index)){
              insertIndex = j
              getResult = true
              break
            }
          }
        }
        if(locate === 0){
          this.dataSourceChangeCopy.splice(insertIndex, 0, {title: tempObj.title, param: tempObj.key, index: locate })
        }else{
          this.dataSourceChangeCopy.splice(insertIndex+1, 0, {title: tempObj.title, param: tempObj.key, index: locate })
        }
        return insertIndex;
      }
    }
  },

  computed: {
    // 选择和默认的选中的处理
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.$store.dispatch('MainTableChecked', selectedRowKeys)
        },
        getCheckboxProps: record => ({
          props: {
            defaultChecked: this.selectedRowKeys.includes(record.key)  // 默认显示
          }
        })
      }
    }
  }
}
</script>


<style lang="less" scoped>
  .content-common-wrap {
    background: #fff;
    margin-top: 5px;
    box-shadow: 0px 1px 1px 1px #ddd;
    padding: 10px;
    box-sizing: border-box;
  }
  .content-main {
    width: 100%;
    border: 1px solid #eee;
    margin-top: 10px;
  }
  
</style>
